<!-- CommentItem.vue -->
<template>
  <div class="comment-item" :class="{ 'child-comment': isChild }">
    <div class="comment-avatar">
      <img :src="comment.user && comment.user.avatar ? comment.user.avatar : '/images/default-avatar.jpg'" alt="用户头像" />
    </div>
    <div class="comment-content">
      <div class="comment-header">
        <div class="user-info">
          <span class="username">{{ comment.user ? comment.user.userName : '未知用户' }}</span>

          <!-- 评分星星 -->
          <div class="rating-stars" v-if="comment.score !== null && comment.score !== undefined">
            <div class="stars">
              <span v-for="n in 5" :key="n" class="star" :class="{ 'filled': n <= Math.round(comment.score) }">★</span>
            </div>
            <span class="score-value">{{ comment.score }}</span>
          </div>
        </div>
        <span class="time" v-if="comment.reDate">{{ formatDate(comment.reDate) }}</span>
      </div>

      <!-- 子评论添加回复指向 -->
      <div class="reply-to" v-if="isChild && comment.upId && parentUserName">
        <span class="reply-to-text">回复 <span class="parent-name">@{{ parentUserName }}</span></span>
      </div>

      <div class="comment-text">{{ comment.remark }}</div>

      <!-- 评论图片 -->
      <div class="comment-images" v-if="comment.picture && comment.picture.length > 0">
        <div class="image-grid" :class="imageGridClass">
          <div v-for="(img, index) in comment.picture" :key="index" class="image-item">
            <img :src="img" @click="previewImage(index)" />
          </div>
        </div>
      </div>

      <div class="comment-footer">
        <div class="actions">
          <button class="action-btn reply-btn" @click="toggleReplyBox">
            <i class="icon-reply"></i> 回复
          </button>
          <button class="action-btn like-btn" @click="likeComment" :class="{ 'liked': isLiked }">
            <i class="icon-like"></i> {{ comment.reLike || 0 }}
          </button>
        </div>
      </div>

      <!-- 子评论区域 -->
      <div class="child-comments-container">
        <!-- 回复框 -->
        <transition name="fade">
          <div class="reply-box" v-if="showReplyInput">
            <div class="reply-avatar">
              <img src="/images/default-avatar.jpg" alt="当前用户头像" />
            </div>
            <div class="reply-input-container">
              <div class="reply-target" v-if="comment.user">回复 @{{ comment.user.userName }}</div>
              <textarea
                  v-model="replyContent"
                  placeholder="写下你的回复..."
                  class="reply-textarea"
                  ref="replyTextarea"
              ></textarea>
              <div class="reply-btns">
                <button @click="cancelReply" class="cancel-btn">取消</button>
                <button @click="submitReply" class="submit-btn" :disabled="!replyContent.trim()">发表回复</button>
              </div>
            </div>
          </div>
        </transition>

        <!-- 子评论列表 -->
        <div class="child-comments" v-if="comment.comments && comment.comments.length > 0">
          <comment-item
              v-for="childComment in comment.comments"
              :key="childComment.remarkId"
              :comment="childComment"
              :is-child="true"
              :parent-user-name="findParentUserName(childComment.upId)"
              @reply="(remarkId, content) => $emit('reply', remarkId, content)"
              @like="(remarkId) => $emit('like', remarkId)"
          ></comment-item>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import { addComment } from '@/api/comment'; // 确保导入你的API函数

export default {
  name: 'CommentItem',
  props: {
    comment: {
      type: Object,
      required: true
    },
    isChild: {
      type: Boolean,
      default: false
    },
    parentUserName: {
      type: String,
      default: ''
    },
    // 新增可选的父级刷新函数
    triggerParentFn: {
      type: Function,
      default: () => {''}
    }
  },
  setup(props, { emit }) {
    const store = useStore();
    const replyContent = ref('');
    const replyTextarea = ref(null);
    const showReplyInput = ref(false);
    const isLiked = ref(false);

    const imageGridClass = computed(() => {
      if (!props.comment.picture) return 'grid-1';

      const count = props.comment.picture.length;
      if (count === 1) return 'grid-1';
      if (count === 2) return 'grid-2';
      if (count === 3) return 'grid-3';
      if (count === 4) return 'grid-4';
      return 'grid-multi';
    });

    const formatDate = (dateStr) => {
      if (!dateStr) return '';

      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return '';

        const now = new Date();
        const diff = now - date;

        // 不到1分钟
        if (diff < 60 * 1000) {
          return '刚刚';
        }

        // 不到1小时
        if (diff < 60 * 60 * 1000) {
          return Math.floor(diff / (60 * 1000)) + '分钟前';
        }

        // 不到1天
        if (diff < 24 * 60 * 60 * 1000) {
          return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
        }

        // 不到1周
        if (diff < 7 * 24 * 60 * 60 * 1000) {
          return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
        }

        // 格式化为年月日
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();

        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
      } catch (e) {
        console.error('日期格式化错误:', e);
        return '';
      }
    };

    // 寻找父评论的用户名（根据upId匹配）
    const findParentUserName = (upId) => {
      if (!upId) return '';

      // 如果upId与当前评论的remarkId相同，返回当前评论的用户名
      if (upId === props.comment.remarkId) {
        return props.comment.user ? props.comment.user.userName : '未知用户';
      }

      // 递归查找子评论中的匹配项
      if (props.comment.comments && props.comment.comments.length > 0) {
        for (const childComment of props.comment.comments) {
          if (childComment.remarkId === upId) {
            return childComment.user ? childComment.user.userName : '未知用户';
          }
        }
      }

      return '';
    };

    const toggleReplyBox = () => {
      showReplyInput.value = !showReplyInput.value;

      // 如果打开了回复框，让文本框自动获取焦点
      if (showReplyInput.value) {
        nextTick(() => {
          if (replyTextarea.value) {
            replyTextarea.value.focus();
          }
        });
      }
    };

    const cancelReply = () => {
      showReplyInput.value = false;
      replyContent.value = '';
    };

    const submitReply = () => {
      if (!replyContent.value.trim()) {
        ElMessage.warning('回复内容不能为空');
        return;
      }

      // 创建新回复评论对象 - 使用API格式，添加upId字段
      const replyComment = {
        remark: replyContent.value,
        score: null, // 回复评论通常没有评分
        reLike: 0,
        reDate: new Date().toLocaleDateString(),
        picture: [], // 回复暂不支持图片
        userId: store.state.userInfo?.userId,
        bindId: props.comment.bindId, // 保持相同的绑定ID
        upId: props.comment.remarkId, // 关键：添加上级父评论ID
        status: 0
      };

      console.log(`提交回复评论:`, replyComment);

      // 使用API提交回复评论
      addComment(replyComment).then((res) => {
        ElMessage.success({
          message: '回复提交成功！',
          type: 'success',
          duration: 2000
        });

        // 调用父组件提供的刷新函数
        props.triggerParentFn();

        // 清空回复框并隐藏
        replyContent.value = '';
        showReplyInput.value = false;

      }).catch(err => {
        ElMessage.error('回复提交失败，请稍后重试');
      });
    };

    const likeComment = () => {
      // 切换点赞状态（仅前端视觉效果）
      isLiked.value = !isLiked.value;

      // 触发点赞事件
      emit('like', props.comment.remarkId);
    };

    const previewImage = (index) => {
      // 这里可以实现图片预览功能
      console.log('预览图片', props.comment.picture[index]);
      // 实际项目中可以使用图片预览组件，例如 v-viewer
    };

    return {
      replyContent,
      replyTextarea,
      showReplyInput,
      isLiked,
      imageGridClass,
      formatDate,
      findParentUserName,
      toggleReplyBox,
      cancelReply,
      submitReply,
      likeComment,
      previewImage
    };
  }
};
</script>

<style scoped>
.comment-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #eaeaea;
  transition: all 0.3s ease;
}

.comment-item:hover {
  background-color: #fafafa;
}

.child-comment {
  margin-left: 48px;
  padding: 16px 0;
  border-bottom: 1px dashed #eaeaea;
}

.comment-avatar {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  margin-right: 16px;
  position: relative;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 2px solid #fff;
}

.comment-content {
  flex-grow: 1;
  position: relative;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 600;
  color: #222;
  font-size: 15px;
}

.time {
  font-size: 13px;
  color: #888;
}

/* 评分星星 */
.rating-stars {
  display: flex;
  align-items: center;
  margin-left: 12px;
}

.stars {
  display: flex;
}

.star {
  color: #e0e0e0;
  font-size: 14px;
}

.star.filled {
  color: #ffb800;
}

.score-value {
  margin-left: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #ffb800;
}

/* 新增回复指向样式 */
.reply-to {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.reply-to-text {
  display: inline-block;
  background-color: #f2f2f2;
  padding: 4px 10px;
  border-radius: 12px;
}

.parent-name {
  color: #10b981;
  font-weight: 500;
}

.comment-text {
  margin-bottom: 14px;
  line-height: 1.7;
  color: #333;
  word-break: break-word;
  font-size: 15px;
}

.comment-images {
  margin: 16px 0;
}

.image-grid {
  display: grid;
  grid-gap: 8px;
  border-radius: 8px;
  overflow: hidden;
}

.grid-1 {
  grid-template-columns: 1fr;
  max-width: 360px;
}

.grid-2 {
  grid-template-columns: 1fr 1fr;
}

.grid-3 {
  grid-template-columns: 1fr 1fr 1fr;
}

.grid-4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.grid-multi {
  grid-template-columns: repeat(3, 1fr);
}

.image-item {
  position: relative;
  overflow: hidden;
  border-radius: 6px;
  aspect-ratio: 1 / 1;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-item:hover img {
  transform: scale(1.05);
}

.comment-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 12px;
}

.actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  background: none;
  border: none;
  padding: 6px 12px;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.reply-btn {
  color: #666;
}

.reply-btn:hover {
  color: #10b981;
  background-color: rgba(16, 185, 129, 0.08);
}

.like-btn {
  color: #666;
}

.like-btn:hover, .like-btn.liked {
  color: #f56565;
  background-color: rgba(245, 101, 101, 0.08);
}

/* 子评论容器，包含回复框和子评论列表 */
.child-comments-container {
  margin-top: 12px;
}

/* 回复框样式 */
.reply-box {
  display: flex;
  margin: 16px 0;
  width: 100%;
}

.reply-avatar {
  width: 36px;
  height: 36px;
  margin-right: 12px;
  flex-shrink: 0;
}

.reply-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.reply-input-container {
  flex-grow: 1;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  background: #f9f9f9;
  padding: 12px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
}

.reply-input-container:focus-within {
  border-color: #10b981;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.1);
}

/* 新增回复目标样式 */
.reply-target {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  padding: 4px 10px;
  background-color: #f0f0f0;
  border-radius: 4px;
  display: inline-block;
}

.reply-textarea {
  width: 100%;
  min-height: 80px;
  border: none;
  background: transparent;
  resize: vertical;
  outline: none;
  padding: 4px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.reply-btns {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.reply-btns button {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.submit-btn {
  background-color: #10b981;
  color: white;
  border: none;
  font-weight: 500;
}

.submit-btn:hover {
  background-color: #059669;
}

.submit-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.cancel-btn {
  background-color: white;
  border: 1px solid #e5e7eb;
  color: #666;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

/* 子评论列表 */
.child-comments {
  margin-top: 12px;
  border-left: 2px solid #eaeaea;
  padding-left: 16px;
}

/* 图标样式 */
.icon-reply:before {
  content: "↩";
  font-size: 14px;
}

.icon-like:before {
  content: "♥";
  font-size: 14px;
}

/* 淡入淡出过渡效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 移动端适配 */
@media (max-width: 576px) {
  .comment-item {
    padding: 16px 0;
  }

  .child-comment {
    margin-left: 36px;
  }

  .comment-avatar {
    width: 40px;
    height: 40px;
    margin-right: 12px;
  }

  .comment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .time {
    margin-left: 0;
  }

  .grid-multi {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>